package com.hl.shifangzhiyu.web;

import com.hl.shifangzhiyu.pojo.PasswordDTO;
import com.hl.shifangzhiyu.pojo.R;
import com.hl.shifangzhiyu.pojo.User;
import com.hl.shifangzhiyu.service.Impl.UserServiceImpl;
import com.hl.shifangzhiyu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserServiceImpl userServiceimpl;
    @PostMapping("/login")
    public R login(@RequestBody User user){
        User loginUser = userService.login(user.getPhone(),userServiceimpl.md5(user.getPassword()));

        if (loginUser != null) {
            return R.ok("登录成功",loginUser);
        }else {
            return R.fail("登录失败");
        }
    }
    @PostMapping("/register")
    public R register(@RequestBody User user){
        System.out.println(user);
        boolean result = userService.register(user);
        if (result) {
            return R.ok("注册成功");
        }else {
            return R.fail("注册失败");
        }
    }
    @PostMapping("/update")
    public R  updateUser(@RequestBody User user) {
        boolean success = userService.updateUser(user);
        if (success) {
            User updatedUser = userService.getById(user.getId());
            return R.ok(updatedUser);
        } else {
            return R.fail("更新失败");
        }
    }

    @GetMapping("/{id}")
    public R getUser(@PathVariable Integer id) {
        User user = userService.getById(id);
        return user != null ? R.ok(user) : R.fail("用户不存在");
    }
    @PostMapping("/change-password")
    public R changePassword(@RequestBody PasswordDTO passwordDTO) {
        boolean success = userService.changePassword(passwordDTO.getUserId(), passwordDTO.getOldPassword(), passwordDTO.getNewPassword());
        return success ? R.ok() : R.fail("原密码错误或修改失败");
    }

}
